const {spawn} = require('child_process');
const os = require('os');
const path = require("path");
const dgram = require('dgram');

function callGo(callback) {
    console.log("call go... ",process.resourcesPath)

    // 构建子程序的实际路径
    let appPath;
    if (process.env.VITE_DEV_SERVER_URL) {
         appPath = './public/fileTs_win.exe';
    } else {
         appPath = path.join(process.resourcesPath, 'public/fileTs_win.exe');
    }
    // 启动Go应用
    const child = spawn(appPath, ['-mode=bg']);

    // 监听标准输出事件
    child.stdout.on('data', (data) => {
        let text = data.toString()
        console.log("stdout >>>:" + text)
        let [valid, cmd, content] = validateAndExtract(text.trim());
        // console.log(valid,cmd,content)
        if (valid) {
            callback({cmd: cmd, content: content})
        }
    });

    // 监听标准错误事件
    child.stderr.on('data', (data) => {
        console.log("stderr >>>:" + data.toString())
    });

    // 监听程序结束事件
    child.on('close', (code) => {
        console.log(`子进程退出，退出码: ${code}`);
    });

    return (message) => {
        child.stdin.write(message + '\n');
    }
}

function getLocalIP() {
    const interfaces = os.networkInterfaces();
    const platform = os.platform();

    // 定义网络接口优先级（从高到低）
    const interfacePriority = {
        'WLAN': 1,        // Wi-Fi 优先
        '以太网': 2,       // 有线网络其次
        '以太网 2': 3,     // 特殊以太网接口（如虚拟机）
        // 可以根据需要添加更多接口名称和优先级
    };

    // 存储符合条件的接口及其优先级
    const validInterfaces = [];

    for (const name of Object.keys(interfaces)) {
        for (const iface of interfaces[name]) {
            // 跳过内部接口和 IPv6
            if (iface.internal || iface.family !== 'IPv4') {
                continue;
            }

            // Windows 系统特殊处理
            if (platform === 'win32') {
                // 排除已知虚拟网络接口
                if (
                    name.includes('vEthernet') ||
                    name.includes('OpenVPN') ||
                    name.includes('WSL') ||
                    name.includes('VMware') ||
                    name.includes('Hyper-V') ||
                    name.includes('Local Area Connection*') ||
                    name.includes('Loopback') ||
                    name.includes('Teredo') ||
                    name.includes('isatap')
                ) {
                    continue;
                }

                // 检查接口是否有默认网关（通过子网掩码判断）
                // 典型家用网络子网掩码是 255.255.255.0 (/24)
                const hasValidSubnet = iface.cidr &&
                    !iface.cidr.startsWith('0.0.0.0') &&
                    !iface.cidr.endsWith('/32'); // 排除主机路由

                if (!hasValidSubnet) {
                    continue;
                }

                // 获取接口优先级
                const priority = interfacePriority[name] || 10; // 默认低优先级

                // 存储符合条件的接口
                validInterfaces.push({
                    address: iface.address,
                    name,
                    priority
                });
            }
            // 其他系统保持原有逻辑
            else {
                if (iface.cidr && !iface.cidr.startsWith('0.0.0.0')) {
                    return iface.address;
                }
            }
        }
    }

    // 如果找到多个有效接口，按优先级排序
    if (validInterfaces.length > 0) {
        validInterfaces.sort((a, b) => a.priority - b.priority);
        // console.log('找到的网络接口:', validInterfaces); // 调试信息
        return validInterfaces[0].address;
    }

    // 回退逻辑
    for (const name of Object.keys(interfaces)) {
        for (const iface of interfaces[name]) {
            if (
                iface.family === 'IPv4' &&
                !iface.internal &&
                iface.cidr &&
                iface.cidr !== '0.0.0.0/0'
            ) {
                return iface.address;
            }
        }
    }

    return '';
}

function validateAndExtract(s) {
    const re = /^\[([^\]]+)\]\s*(.*)$/;
    const matches = s.match(re);

    if (!matches || matches.length < 3) {
        return [false, "", ""];
    }

    // 明确指定捕获组的索引类型
    return [true, matches[1], matches[2]];
}


class ChatService {
    constructor(receiveCallback) {
        this.serverPort = 3000;
        this.socket = dgram.createSocket('udp4');
        this.setupSocketListeners(receiveCallback);
    }

    setupSocketListeners(receiveCallback) {
        this.socket.on('error', (err) => {
            console.error(`Socket error: ${err.message}`);
            this.socket.close();
        });

        this.socket.on('message', (msg, rinfo) => {
            let message = msg.toString();

            if (!(/^\[.*]$/.test(message))) {
                console.debug(`收到来自 ${rinfo.address}的消息: ${message}`);
                receiveCallback({"from": rinfo.address, message: message })
            } else {
                console.debug(`收到命令消息: ${message}`);
            }
        });
    }

    // UDP 发送方法（带 Promise 封装）
    async chatSend(message, remoteIp) {
        return new Promise((resolve) => {
            const buffer = Buffer.from(message);

            this.socket.send(buffer, this.serverPort, remoteIp, (err) => {
                const success = !err;
                if (!success) {
                    console.error('发送失败:', err);
                }
                resolve(success);
            });
        });
    }

    // 启动服务
    start() {
        this.socket.bind(this.serverPort, () => {
            console.log(`ChatService 已启动，监听端口 ${this.serverPort}`);
        });
    }

    // 关闭服务
    stop() {
        this.socket.close(() => {
            console.log('ChatService 已停止');
        });
    }
}


module.exports = {
    callGo,
    getLocalIP,
    ChatService,
};
